package com.ws.config.config;

import cn.hutool.core.util.StrUtil;

import com.ws.user.user.entity.User;
import com.ws.user.user.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroRealm extends AuthorizingRealm {

	 /**
     * 获取身份验证信息
     * Shiro中，最终是通过 Realm 来获取应用程序中的用户、角色及权限信息的。
     *
     * @param authenticationToken 用户身份信息 token
     * @return 返回封装了用户信息的 AuthenticationInfo 实例
     */

	 @Autowired
	 IUserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName=token.getUsername();

        /*验证用户名*/
        if(StrUtil.isEmpty(userName)){
            return null;
        }
        User user=userService.readByUserName(userName);
        if(user==null ||  !StrUtil.equals(user.getUserName(),userName)){
            return null;
        }

        //返回用户信息  会自动判断密码
        return  new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

    /**
     * 获取授权信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("————权限认证————");
        System.out.println("-------------");
        User user=(User) SecurityUtils.getSubject().getPrincipal();
        String username = user.getUserName();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获得该用户角色
      /*  String role = "manager";
        Set<String> set = new HashSet<>();
        //需要将 role 封装到 Set 作为 info.setRoles() 的参数
        set.add(role);
        //设置该用户拥有的角色
        info.setRoles(set);
        info.addStringPermission("789");
        info.addStringPermission("123:456");
        return info;*/
        info.addStringPermission("user:add");
        return info;
    }
	
}
